import pandas as pd
import os,csv
import argparse


def get_AMQAP_(x):
    MQlist=[]
    for MQ in x:
        MQlist.append(ord(MQ)-33)
    AMQ = int(sum(MQlist)/len(MQlist))
    return AMQ

def get_AMQAP_readfile(inputPath):
    column_names = ['chr', 'position', 'mappingQ']
    df=pd.read_csv(inputPath, quoting=csv.QUOTE_NONE, header=None, names=column_names, sep='\t')
    df['AMQS'] = df["mappingQ"].apply(get_AMQAP_)
    return df


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="get average Mapping Quality at a position.")
    parser.add_argument('-i', "--input", help="Using mpileup get the txt file from bam.")
    parser.add_argument('-o', "--output", help="outfilePath")
    # parser.add_argument('-l', "--log", help="Log file path.", default="./")
    # parser.add_argument('-n', "--number", type=int, help="The number of generate sequence.", default="10")
    args = parser.parse_args()
    resultDf=get_AMQAP_readfile(args.input)
    # re dataframe
    # 新建一列第三列是第二列的数字+1
    resultDf['positionEnd'] = resultDf.iloc[:, 1] + 1
    df_new = resultDf.reindex(columns=['chr', 'position', 'positionEnd', 'AMQS'])
    df_new.to_csv(args.output, header=False, index=False, sep='\t')

